//
//  IWxChatMgrChat.m
//  WxSdk
//
//  Created by fusuwei on 14-9-11.
//  Copyright (c) 2014年 网信金融集团. All rights reserved.
//

#import "IWxChatMgrChat.h"
#import "UcfgroupXMPPManger.h"
#import "Utility.h"
#include "PublicMacros.h"
#include "EPublicMacros.h"
#import "ChatMessageMgr.h"
#import "ChatContactMgr.h"
#import "HttpURLConnection.h"
#import "XMPPHTTPFileUpload.h"
#import "NSString+Time.h"

@protocol HttpURLConnectionDelegate;


@interface IWxChatMgrChat() <HttpURLConnectionDelegate,XMPPHTPPFileUploadDelegate>
{
    NSString *pre_messageId;
}
/**
 *  上传文件相关的参数
 */
@property (nonatomic,copy)NSString *uploadFilePath;//要上传的本地文件路径
@property (nonatomic,copy)NSString *saveFilePath;//保存到本地可以播放、显示的路径 因为音频的播放路径比上传路径多一个file:// so 做了一个处理
@property (nonatomic,assign)BOOL isGroup;//YES  NO
@property (nonatomic,copy)NSString *contactJidNameValid;
@property (nonatomic,copy)NSString *contactDesc;//文件描述
@property (nonatomic,copy)NSString *fileType;// 文件类型 －图片type=2 视频type=3 音频type=4 普通文件type=5
@property (nonatomic, strong)NSString *contentType;// text/plain：纯文本 image/*：图片 audio/*：语音 video/*视频 */*：文件
@property (nonatomic,assign)NSInteger fileDuration;//时长、主要针对语音和视频
@property (nonatomic,assign) long fileSize;//文件大小


@property (nonatomic,weak) id<IChatProgressDelegate>delegateprogress;
@property (nonatomic,weak) id<EWxChatMgrChatDelegate>delegate;

@end


@implementation IWxChatMgrChat

static IWxChatMgrChat *sharedInstance = nil;

+ (IWxChatMgrChat *)sharedInstance
{
    @synchronized(self)
    {
        if (sharedInstance == nil )
        {
            sharedInstance = [[self alloc] init];
        }
    }
    
    return sharedInstance;
}

-(id)init
{
	self=[super init];
	if(self)
    {
        
    }
	return self;
}

/*!
 @method
 @brief  发送文本消息
 @param  contactId     接收消息好友id
 @param  messageBody   文本消息内容  最大长度为 kMessageBodyMaxLen
 @result 返回值         非空，为消息id
         回调方法        sendMessageRspState:messageId:error: 有发送状态返回
 */
- (NSString *)sendMessageText:(NSString *)messageBody
                    toContact:(NSString *)contactId
                  isGroupChat:(BOOL)isyes
                     delegate:(id)delegate
{
    WXLog(@"sendMessageText:contactId= %@",contactId);
    self.isGroup = isyes;
    if ([messageBody length] > kMessageBodyMaxLen)
    {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_MessageBodyMaxLen_Error"];
        return @"";
    }
    if (contactId == nil || [contactId isEqualToString:@""])
    {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_contactId_Error"];
        return @"";
    }
    NSString *jidNameValid = [self convertToJid:contactId isGroup:isyes];
    NSString *contactName = nil;
    
    NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
    [body setStringValue:messageBody];
    NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
    if (isyes)
    {
        [message addAttributeWithName:@"type" stringValue:@"groupchat"];
        contactName = [ChatGroupMgr fetchGroupNameByGroupId:contactId];
    }
    else
    {
        [message addAttributeWithName:@"type" stringValue:@"chat"];
        contactName = [ChatContactMgr fetchNameByContactId:contactId];
        
    }
    
    NSString *messageId = [NSString stringWithFormat:@"%@_%d",[NSString stringFromDate:[NSDate date]],[self getRandomNumber:1000000 to:9000000]];
    [message addAttributeWithName:@"id" stringValue:messageId];
    
    NSString *to = jidNameValid;
    
    [message addAttributeWithName:@"to" stringValue:to];
    [message addChild:body];
    
    NSXMLElement *contentType = [NSXMLElement elementWithName:@"contentType"];
    [contentType setStringValue:@"text"];
    
    NSXMLElement *request = [NSXMLElement elementWithName:@"request" xmlns:@"urn:xmpp:receipts"];
    [message addChild:contentType];
    [message addChild:request];
    
    //创建MessageBase对象并保存到数据库ChatMessage表中
    MessageBase *wxmsg = [[MessageBase alloc] init];
    wxmsg.messageId = messageId;
    wxmsg.messageType = ChatMsgBody_Text;
    wxmsg.messageBody = messageBody;
    wxmsg.createTime = [NSString stringFromDate:[NSDate date]];
    
    wxmsg.messageStatus = Chat_Send_Sending;

    wxmsg.contactId = [Utility getBareContactId:to];
    
    wxmsg.contactName = contactName;
    wxmsg.isIncoming = Msg_Out;
    wxmsg.isGroupMsg = isyes;
    wxmsg.frommemberID = kUserLoginName;
    
    wxmsg.isRead = YES;
    wxmsg.duration = 0;
    wxmsg.content = None;
    wxmsg.thumbnail = None;
    
    wxmsg.localFileUrl = None;
    wxmsg.serverFileName = None;
    wxmsg.fileSize = 0;
    wxmsg.fileName = None;
    
    [ChatMessageMgr saveChatMessageObj:wxmsg];
    
    [[UcfgroupXMPPManger sharedInstance].xmppStream sendElement:message];
    
    //将要发送消息
    [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Sending messageId:wxmsg.messageId error:nil];
    
    [[UcfgroupXMPPManger sharedInstance] addXmppRecordReqId:messageId type:@"sendMessageRspState:messageId:error:" paraMsg:wxmsg.messageId];
    return messageId;
}
/*!
  @method
  @brief  发送文件消息消息
  @param  contactId     接收消息好友id
  @param  messageBody   文本消息内容  最大长度为 kMessageBodyMaxLen
  @result 返回值         非空，为消息id
  回调方法        sendMessageRspState:messageId:error: 有发送状态返回
  */
- (NSString *)sendFileText:(NSString *)messageBody
                    toContact:(NSString *)contactId
                  isGroupChat:(BOOL)isyes
                     delegate:(id)delegate
{
    NSString *messageId = [NSString stringWithFormat:@"%@_%d",[NSString stringFromDate:[NSDate date]],[self getRandomNumber:1000000 to:9000000]];
    NSString *jidNameValid = [self convertToJid:contactId isGroup:isyes];
    self.contactJidNameValid = jidNameValid;
    [self sendFilesWithMsgID:messageId
                 messageBody:messageBody
                 toContactID:jidNameValid
               localFileName:@"文件名称"
                   servieUrl:@"文件服务器地址"
                    fileType:@"*/*"
                    fileSize:123
                 isGroupChat:isyes
                    duration:0];
    return messageId;
}
/**
 *  仅把数据存入数据库，不执行发送操作
 *
 *  @param contactId
 *  @param messageBody
 *  @param isyes       
 */
- (NSString *)textMessageOnlySvaeDBContavtID:(NSString *)contactId
                               message:(NSString *)messageBody
                               isGroup:(BOOL)isyes
{
    NSString *jidNameValid = [self convertToJid:contactId isGroup:isyes];
    NSString *contactName = nil;
    
    NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
    [body setStringValue:messageBody];
    NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
    if (isyes)
    {
        [message addAttributeWithName:@"type" stringValue:@"groupchat"];
        contactName = [ChatGroupMgr fetchGroupNameByGroupId:contactId];
    }
    else
    {
        [message addAttributeWithName:@"type" stringValue:@"chat"];
        contactName = [ChatContactMgr fetchNameByContactId:contactId];
        
    }
    
    NSString *messageId = [NSString stringWithFormat:@"%@_%d",[NSString stringFromDate:[NSDate date]],[self getRandomNumber:1000000 to:9000000]];
    [message addAttributeWithName:@"id" stringValue:messageId];
    
    NSString *to = jidNameValid;
    
    [message addAttributeWithName:@"to" stringValue:to];
    [message addChild:body];
    
    NSXMLElement *request = [NSXMLElement elementWithName:@"request" xmlns:@"urn:xmpp:receipts"];
    [message addChild:request];
    
    //创建MessageBase对象并保存到数据库ChatMessage表中
    MessageBase *wxmsg   = [[MessageBase alloc] init];
    wxmsg.messageId      = messageId;
    wxmsg.messageType    = ChatMsgBody_Text;
    wxmsg.messageBody    = messageBody;
    wxmsg.createTime     = [NSString stringFromDate:[NSDate date]];
    wxmsg.messageStatus  = Chat_Send_Success;//显示发送成功
    wxmsg.contactId      = [Utility getBareContactId:to];
    wxmsg.contactName    = contactName;
    wxmsg.isIncoming     = Msg_Out;
    wxmsg.isGroupMsg     = isyes;
    wxmsg.frommemberID   = kUserLoginName;
    wxmsg.isRead         = YES;
    wxmsg.duration       = 0;
    wxmsg.content        = None;
    wxmsg.thumbnail      = None;
    wxmsg.localFileUrl   = None;
    wxmsg.serverFileName = None;
    wxmsg.fileSize       = 0;
    wxmsg.fileName       = None;
    [ChatMessageMgr saveChatMessageObj:wxmsg];
    
    return messageId;
}


#pragma mark - XMPPHTPPFileUploadDelegate
- (void)xmppHTTPFileUpload:(XMPPHTTPFileUpload *)sender didAssignSlot:(XMPPSlot *)slot
{
#warning message - 将它的代理移除－否则上传文件会被叠加！！！！
    [sender removeDelegate:self delegateQueue:dispatch_get_main_queue()];

    //上传文本
    NSURL *URL = [NSURL URLWithString:[slot.put stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    request.HTTPMethod = @"PUT";
    [request setValue:@"application/octet-stream" forHTTPHeaderField:@"Content-Type"];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionUploadTask *uploadFileTask = [session uploadTaskWithRequest:request
                                                                   fromFile:[NSURL URLWithString:[self.uploadFilePath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]
                                                          completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                                              
                                                              if (error)
                                                              {
                                                                  //弹出失败提示
                                                                  [self.delegate sendMessageRspState:Chat_Send_Failure
                                                                                           messageId:pre_messageId
                                                                                               error:[NSString stringWithFormat:@"%@发送失败",self.contactDesc]];
                                                              }else{
                                                                  [self sendFilesWithMsgID:pre_messageId
                                                                               messageBody:self.contactDesc
                                                                               toContactID:self.contactJidNameValid
                                                                             localFileName:self.saveFilePath
                                                                                 servieUrl:slot.put
                                                                                  fileType:self.contentType
                                                                                  fileSize:self.fileSize
                                                                               isGroupChat:self.isGroup
                                                                                  duration:self.fileDuration];
                                                              }
                                                              
                                                             
                                                }];
    
    [uploadFileTask resume];
    
}

- (void)xmppHTTPFileUpload:(XMPPHTTPFileUpload *)sender didFailToAssignSlotWithError:(XMPPIQ *) iqError
{
    [sender removeDelegate:self delegateQueue:dispatch_get_main_queue()];
    if (self.delegate && [self.delegate respondsToSelector:@selector(sendMessageRspState:messageId:error:)]) {
        [self.delegate sendMessageRspState:Chat_Send_Failure messageId:pre_messageId
                                     error:[NSString stringWithFormat:@"%@发送失败",self.contactDesc]];
    }
}

#pragma mark - Public methods

/*!
 @method
 @brief  发送图片文件消息
 @param  contactId 接收消息好友id
 @param  fileUrl   图片文件全路径名称
 @param  desc      图片文件描述  最大长度kGroupDescribeMaxLen
 @param  progress  进度条的代理回调，若不用可以传nil
 @result 返回值     非空，为消息id
         回调方法   sendMessageRspState:messageId:error: 有发送状态返回
 */
- (NSString *)sendMessageImageToContact:(NSString *)contactId
                           imagefileURL:(NSString *)imagefileURL
                                   desc:(NSString *)desc
                            isGroupChat:(BOOL)isyes
                               progress:(id<IChatProgressDelegate>)progress
{
    WXLog(@"sendMessageImageToContact= %@",contactId);
    if (contactId == nil) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_contactId_Error"];
        return @"";
    }
    if (imagefileURL == nil)
    {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_fileUrl_Error"];
        return @"";
    }
    if (![self isFileExist:imagefileURL])
    {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_fileUrl_Error"];
        return @"";
    }
    
    if ([desc length] > kGroupDescribeMaxLen)
    {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_descMaxLen_Error"];
        return @"";
    }
    
   self.fileSize = [self fileSizeAtPath:imagefileURL];
    if (self.fileSize > kFileSizeMaxLen)
    {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"kFileSizeMaxLen_Error"];
        return @"kFileSizeMaxLen_Error";
    }
    
    self.isGroup        = isyes;
    self.fileType       = @"2";
    self.contentType    = @"image";
    self.fileDuration   = 0;
    self.contactDesc    = desc;
    self.uploadFilePath = imagefileURL;
    self.saveFilePath   = imagefileURL;
    
    NSString *jidNameValid = [self convertToJid:contactId isGroup:isyes];
    self.contactJidNameValid = jidNameValid;
    self.delegateprogress    = progress;
    pre_messageId = [NSString stringWithFormat:@"%@_%d",[NSString stringFromDate:[NSDate date]],[self getRandomNumber:1000000 to:9000000]];
    NSString *contactName = nil;
    if (isyes)
    {
        contactName = [ChatGroupMgr fetchGroupNameByGroupId:[Utility getBareContactId:contactId]];
    }
    else
    {
        contactName = [ChatContactMgr fetchNameByContactId:[Utility getBareContactId:contactId]];
    }
    //创建ChatMessage对象并保存到数据库表
    MessageBase *wxmsg  = [[MessageBase alloc] init];
    wxmsg.messageId     = pre_messageId;
    wxmsg.messageType   = [self.fileType integerValue];
    wxmsg.messageBody   = desc;
    wxmsg.createTime    = [NSString stringFromDate:[NSDate date]];

    wxmsg.messageStatus = Chat_Send_Sending;
    wxmsg.contactId     = [Utility getBareContactId:contactId];

    wxmsg.contactName   = contactName;
    wxmsg.isIncoming    = Msg_Out;
    wxmsg.isGroupMsg    = isyes;
    wxmsg.frommemberID = kUserLoginName;

    wxmsg.isRead = YES;
    wxmsg.duration = self.fileDuration;

    wxmsg.thumbnail      = None;
    wxmsg.localFileUrl   = [imagefileURL lastPathComponent];
    wxmsg.serverFileName = None;
    wxmsg.fileSize       = 0;
    wxmsg.fileName       = [imagefileURL lastPathComponent];
    
    [ChatMessageMgr saveChatMessageObj:wxmsg];
    
    //contentsAtPath  取出文件的data
    NSFileManager* manager = [NSFileManager defaultManager];
    NSData *data           = [manager contentsAtPath:imagefileURL];
    UIImage *image = [UIImage imageWithData:data];
    __weak typeof(self)weakself = self;
    [NetWork PostUpLoadImageWithImages:image index:1 pid:@"" successBlock:^(NSString *webimagepath) {
        [weakself sendFilesWithMsgID:pre_messageId
                         messageBody:weakself.contactDesc
                         toContactID:weakself.contactJidNameValid
                       localFileName:weakself.saveFilePath
                           servieUrl:webimagepath
                            fileType:weakself.contentType
                            fileSize:weakself.fileSize
                         isGroupChat:weakself.isGroup
                            duration:weakself.fileDuration];
    } FailureBlock:^(NSString *msg) {
        //弹出失败提示
        [weakself.delegate sendMessageRspState:Chat_Send_Failure
                                     messageId:pre_messageId
                                         error:[NSString stringWithFormat:@"%@发送失败",weakself.contactDesc]];
    } errorBlock:^(id error) {
        if (weakself.delegate && [weakself.delegate respondsToSelector:@selector(sendMessageRspState:messageId:error:)]) {
            [weakself.delegate sendMessageRspState:Chat_Send_Failure messageId:pre_messageId
                                             error:[NSString stringWithFormat:@"%@发送失败",weakself.contactDesc]];
        }
    }];
   
   // [[UcfgroupXMPPManger sharedInstance] sendFileForSize:self.fileSize
   //                                             fileName:imagefileURL
   //                                             fileDate:data
    //                                         andDelegate:self];
    
    return pre_messageId;
}




/*!
 @method
 @brief  发送音频消息
 @param  contactId      接收消息好友id
 @param  voiceFileURL   音频消息资源文件路径
 @param  desc           文件描述  最大长度kGroupDescribeMaxLen
 @param  duration       语音时长
 @param  progress       进度条的代理回调，若不用可以传nil
 @result 返回值          非空，为消息id
         回调方法        sendMessageRspState:messageId:error: 有发送状态返回
*/
- (NSString  *)sendMessageVoiceToContact:(NSString *)contactId
                            voiceFileURL:(NSString *)voiceFileURL
                                duration:(NSInteger)duration
                                    desc:(NSString *)desc
                             isGroupChat:(BOOL)isyes
                                progress:(id<IChatProgressDelegate>)progress
{
    WXLog(@"sendMessage:user= %@",contactId);
    if (contactId == nil) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_contactId_Error"];
        return @"";
    }
    if (voiceFileURL == nil) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_fileUrl_Error"];
        return @"";
    }
    
    if (![self isFileExist:voiceFileURL]) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_fileUrl_Error"];
        return @"";
    }
    
    if ([desc length] > kGroupDescribeMaxLen) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_descMaxLen_Error"];
        return @"";
    }
    
    self.fileSize = [self fileSizeAtPath:voiceFileURL];
    if (self.fileSize > kFileSizeMaxLen)
    {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"kFileSizeMaxLen_Error"];
        return @"";
    }
    
    self.fileType         = @"4";
    self.contentType      = @"audio";
    self.fileDuration     = duration;
    self.contactDesc      = desc;
    self.uploadFilePath   = voiceFileURL;
    self.saveFilePath     = voiceFileURL;
    self.delegateprogress = progress;
    self.isGroup          = isyes;
    //contentsAtPath  取出文件的data
    NSFileManager* manager = [NSFileManager defaultManager];
    NSData *data           = [manager contentsAtPath:voiceFileURL];
    
    NSString *jidNameValid = [self convertToJid:contactId isGroup:isyes];
    self.contactJidNameValid = jidNameValid;

    pre_messageId = [NSString stringWithFormat:@"%@_%d",[NSString stringFromDate:[NSDate date]],[self getRandomNumber:1000000 to:9000000]];
    NSString *contactName = nil;
    if (isyes)
    {
        contactName = [ChatGroupMgr fetchGroupNameByGroupId:[Utility getBareContactId:contactId]];
    }
    else
    {
        contactName = [ChatContactMgr fetchNameByContactId:[Utility getBareContactId:contactId]];
    }
    //创建ChatMessage对象并保存到数据库表
    MessageBase *wxmsg  = [[MessageBase alloc] init];
    wxmsg.messageId     = pre_messageId;
    wxmsg.messageType   = [self.fileType integerValue];
    wxmsg.messageBody   = desc;
    wxmsg.createTime    = [NSString stringFromDate:[NSDate date]];

    wxmsg.messageStatus = Chat_Send_Sending;
    wxmsg.contactId     = [Utility getBareContactId:contactId];

    wxmsg.contactName   = contactName;
    wxmsg.isIncoming    = Msg_Out;
    wxmsg.isGroupMsg    = isyes;
    wxmsg.frommemberID = kUserLoginName;

    wxmsg.isRead        = YES;
    wxmsg.duration      = duration;

    wxmsg.localFileUrl   = [voiceFileURL lastPathComponent];
    wxmsg.serverFileName = None;
    wxmsg.fileSize       = self.fileDuration;
    wxmsg.fileName       = [voiceFileURL lastPathComponent];
    
    [ChatMessageMgr saveChatMessageObj:wxmsg];
    
//    __weak typeof(self)weakself = self;
//    [NetWork PostUpLoadAudioWithData:data successBlock:^(NSString *webimagepath) {
//
//        [weakself sendFilesWithMsgID:pre_messageId
//                         messageBody:weakself.contactDesc
//                         toContactID:weakself.contactJidNameValid
//                       localFileName:weakself.saveFilePath
//                           servieUrl:webimagepath
//                            fileType:weakself.contentType
//                            fileSize:weakself.fileSize
//                         isGroupChat:weakself.isGroup
//                            duration:weakself.fileDuration];
//
//    } FailureBlock:^(NSString *msg) {
//        //弹出失败提示
//        [weakself.delegate sendMessageRspState:Chat_Send_Failure
//                                     messageId:pre_messageId
//                                         error:[NSString stringWithFormat:@"%@发送失败",weakself.contactDesc]];
//    } errorBlock:^(id error) {
//
//        if (weakself.delegate && [weakself.delegate respondsToSelector:@selector(sendMessageRspState:messageId:error:)]) {
//            [weakself.delegate sendMessageRspState:Chat_Send_Failure messageId:pre_messageId
//                                             error:[NSString stringWithFormat:@"%@发送失败",weakself.contactDesc]];
//        }
//
//    }];

    
    [[UcfgroupXMPPManger sharedInstance] sendFileForSize:self.fileSize
                                                fileName:voiceFileURL
                                                fileDate:data
                                             andDelegate:self];
//    保存聊天文件
    [[UcfgroupXMPPManger sharedInstance] saveChatFileName:[voiceFileURL lastPathComponent]
                                                 withData:[NSData dataWithContentsOfFile:voiceFileURL]];
    

    
    return pre_messageId;
}

/*!
 @method
 @brief  发送视频消息
 @param  contactId     接收消息好友id
 @param  videoFileURL  视频消息资源文件路径
 @param  desc          文件描述  最大长度kGroupDescribeMaxLen
 @param  duration      文件播放或录制时长
 @result 返回值         非空，为消息id
         回调方法        sendMessageRspState:messageId:error: 有发送状态返回
 */
- (NSString *)sendMessageVideoToContact:(NSString *)contactId
                           videoFileURL:(NSString *)videoFileURL
                               duration:(NSInteger)duration
                                   desc:(NSString *)desc
                            isGroupChat:(BOOL)isyes
                               progress:(id<IChatProgressDelegate>)progress
{
    self.fileType = @"3";
    self.contentType = @"video/*";
    self.fileDuration = duration;

    WXLog(@"sendMessageVideoToContact:user= %@",contactId);
    if (contactId == nil || [contactId isEqualToString:@""]) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_contactId_Error"];
        return @"";
    }
    if (videoFileURL == nil || [videoFileURL  isEqualToString:@""]) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_fileUrl_Error"];
        return @"";
    }
    if (![self isFileExist:videoFileURL]) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_fileUrl_Error"];
        return @"";
    }
    
    if ([desc length] > kGroupDescribeMaxLen) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_descMaxLen_Error"];
        return @"";
    }
    
    self.fileSize = [self fileSizeAtPath:videoFileURL];
    if (self.fileSize > kFileSizeMaxLen)
    {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"kFileSizeMaxLen_Error"];
        return @"";
    }
    
    //保存聊天文件
 //   [[UcfgroupXMPPManger sharedInstance] saveChatFileName:[videoFileURL lastPathComponent] withData:[NSData dataWithContentsOfFile:videoFileURL]];
    
    
    //contentsAtPath  取出文件的data
    NSFileManager* manager = [NSFileManager defaultManager];
    NSData *data = [manager contentsAtPath:videoFileURL];
    self.contactDesc = desc;
    
    
    NSString *jidNameValid = [self convertToJid:contactId isGroup:isyes];
    self.uploadFilePath = videoFileURL;
    self.contactJidNameValid = jidNameValid;
    self.delegateprogress = progress;
    self.saveFilePath = [videoFileURL lastPathComponent];
    self.isGroup = isyes;
    
    [[UcfgroupXMPPManger sharedInstance] sendFileForSize:self.fileSize
                                                fileName:videoFileURL
                                                fileDate:data
                                             andDelegate:self];

    

    
    pre_messageId = [NSString stringWithFormat:@"%@_%d",[NSString stringFromDate:[NSDate date]],[self getRandomNumber:1000000 to:9000000]];
    {
        NSString *contactName = nil;
        if (isyes)
        {
            contactName = [ChatGroupMgr fetchGroupNameByGroupId:[Utility getBareContactId:contactId]];
        }
        else
        {
            contactName = [ChatContactMgr fetchNameByContactId:[Utility getBareContactId:contactId]];
        }
        //创建ChatMessage对象并保存到数据库表
        MessageBase *wxmsg = [[MessageBase alloc] init];
        wxmsg.messageId     = pre_messageId;
        wxmsg.messageType   = [self.fileType integerValue];
        wxmsg.messageBody   = desc;
        wxmsg.createTime    = [NSString stringFromDate:[NSDate date]];
        wxmsg.messageStatus = Chat_Send_Sending;
        wxmsg.contactId     = [Utility getBareContactId:contactId];
        wxmsg.contactName   = contactName;
        wxmsg.isIncoming    = Msg_Out;
        wxmsg.isGroupMsg    = isyes;
        wxmsg.localFileUrl  = videoFileURL;
        wxmsg.isRead = YES;
        wxmsg.duration = 0;
        if ([self.fileType integerValue] >=100)
        {
            wxmsg.messageBody = None;
            wxmsg.content = desc;
        }
        else
        {
            wxmsg.content = None;
        }
        wxmsg.thumbnail = None;
        
        wxmsg.localFileUrl = [videoFileURL lastPathComponent];
        wxmsg.serverFileName = None;
        wxmsg.fileSize = 0;
        wxmsg.fileName = None;
        
        [ChatMessageMgr saveChatMessageObj:wxmsg];
    }
        
    return pre_messageId;
}

/*!
 @method
 @brief  发送自定义消息
 @param  contactId    接收消息好友id
 @param  content      自定义消息内容  最大长度kMessageBodyMaxLen
 @param  msgtype      消息类型值必须大于100  否则，返回Chat_msgtype_Error
 @result 返回值        非空，为消息id
         回调方法       sendMessageRspState:messageId:error: 有发送状态返回
 */
- (NSString *)sendCustomerMessage:(NSString *)content toContact:(NSString *)contactId msgtype:(NSInteger)msgtype
{
    WXLog(@"sendCustomerMessage contactId= %@",contactId);
    if (msgtype < 100) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_msgtype_Error"];
        return @"";
    }
    if (contactId == nil || [contactId isEqualToString:@""]) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_contactId_Error"];
        return @"";
    }
    
    if ([content length] > kMessageBodyMaxLen) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_MessageBodyMaxLen_Error"];
        return @"";
    }
    
    NSString *jidNameValid = [self convertToJid:contactId isGroup:NO];

    NSString *contactName = nil;
    NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
    [body setStringValue:content];
    NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
    NSString *messageId = [NSString stringWithFormat:@"%@_%d",[NSString stringFromDate:[NSDate date]],[self getRandomNumber:1000000 to:9000000]];
    [message addAttributeWithName:@"id" stringValue:messageId];
    
    [message addAttributeWithName:@"to" stringValue:jidNameValid];
    [message addChild:body];
    
    NSXMLElement *ext = [NSXMLElement elementWithName:@"ext"];
    [ext addAttributeWithName:@"type" stringValue:[NSString stringWithFormat:@"%ld", (long)msgtype]];
    [message addChild:ext];
    NSXMLElement *request = [NSXMLElement elementWithName:@"request" xmlns:@"urn:xmpp:receipts"];
    [message addChild:request];
    
    //创建MessageBase对象并保存到数据库ChatMessage表中
    MessageBase *wxmsg = [[MessageBase alloc] init];
    wxmsg.messageId = messageId;
    wxmsg.messageType = msgtype;
    wxmsg.messageBody = content;
    wxmsg.createTime = [NSString stringFromDate:[NSDate date]];
    
    wxmsg.messageStatus = Chat_Send_Sending;
    
    wxmsg.contactId = [Utility getBareContactId:jidNameValid];
    
    wxmsg.contactName = contactName;
    wxmsg.isIncoming = Msg_Out;
    wxmsg.isGroupMsg = NO;
    
    wxmsg.isRead = YES;
    wxmsg.duration = 0;
    wxmsg.content = None;
    wxmsg.thumbnail = None;
    
    wxmsg.localFileUrl = None;
    wxmsg.serverFileName = None;
    wxmsg.fileSize = 0;
    wxmsg.fileName = None;
    
    [ChatMessageMgr saveChatMessageObj:wxmsg];
    
    [[UcfgroupXMPPManger sharedInstance].xmppStream sendElement:message];
    
    //将要发送消息
    [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Sending messageId:wxmsg.messageId error:nil];
    
    [[UcfgroupXMPPManger sharedInstance] addXmppRecordReqId:messageId type:@"sendMessageRspState:messageId:error:" paraMsg:wxmsg.messageId];
    return messageId;
}
/*!
 @method
 @brief  发送普通文件消息
 @param  contactId   接收消息好友id
 @param  fileUrl     文件全路径名称
 @param  desc        文件描述  最大长度kGroupDescribeMaxLen
 @param  progress    进度条的代理回调，若不用可以传nil
 @result 返回值       非空，为消息id
         回调方法      sendMessageRspState:messageId:error: 有发送状态返回
 */
- (NSString *)sendMessageFileToContact:(NSString *)contactId fileURL:(NSString *)fileURL desc:(NSString *)desc isGroupChat:(BOOL)isyes progress:(id<IChatProgressDelegate>)progress
{
    WXLog(@"sendMessageFileToContact= %@",contactId);
    
    if (contactId == nil) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_contactId_Error"];
        return @"";
    }
    if (fileURL == nil) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_fileUrl_Error"];
        return @"";
    }
    
    if (![self isFileExist:fileURL]) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_fileUrl_Error"];
        return @"";
    }
    
    if ([desc length] > kGroupDescribeMaxLen) {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"Chat_descMaxLen_Error"];
        return @"";
    }
    
    long long fileSize = [self fileSizeAtPath:fileURL];
    if (fileSize > kFileSizeMaxLen)
    {
        [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Failure messageId:nil error:@"kFileSizeMaxLen_Error"];
        return @"";
    }
    
    //保存聊天文件
   // [[UcfgroupXMPPManger sharedInstance] saveChatFileName:[fileURL lastPathComponent] withData:[NSData dataWithContentsOfFile:fileURL]];
    
    NSString *jidNameValid = [self convertToJid:contactId isGroup:isyes];
    
    self.delegateprogress = progress;
    
    pre_messageId = [NSString stringWithFormat:@"%@_%d",[NSString stringFromDate:[NSDate date]],[self getRandomNumber:1000000 to:9000000]];
    {
        NSString *contactName = nil;
        if (isyes)
        {
            contactName = [ChatGroupMgr fetchGroupNameByGroupId:[Utility getBareContactId:contactId]];
        }
        else
        {
            contactName = [ChatContactMgr fetchNameByContactId:[Utility getBareContactId:contactId]];
        }
        self.fileType = @"5";
        self.contentType = @"*/*";
        //创建ChatMessage对象并保存到数据库表
        MessageBase *wxmsg = [[MessageBase alloc] init];
        wxmsg.messageId = pre_messageId;
        wxmsg.messageType = [self.fileType integerValue];
        wxmsg.messageBody = desc;
        wxmsg.createTime = [NSString stringFromDate:[NSDate date]];
        
        wxmsg.messageStatus = Chat_Send_Sending;
        wxmsg.contactId = [Utility getBareContactId:contactId];
        
        wxmsg.contactName = contactName;
        wxmsg.isIncoming = Msg_Out;
        wxmsg.isGroupMsg = isyes;
        
        wxmsg.isRead = YES;
        wxmsg.duration = 0;
        if ([self.fileType integerValue] >=100)
        {
            wxmsg.messageBody = None;
            wxmsg.content = desc;
        }
        else
        {
            wxmsg.content = None;
        }
        wxmsg.thumbnail = None;
        
        wxmsg.localFileUrl = [fileURL lastPathComponent];
        wxmsg.serverFileName = None;
        wxmsg.fileSize = 0;
        wxmsg.fileName = None;
        
        [ChatMessageMgr saveChatMessageObj:wxmsg];
    }
    
    NSString *localfilename = [fileURL lastPathComponent];
    
    //    [UploadFile sharedInstance].logRegWxUserObject = [UcfgroupXMPPManger sharedInstance].logRegWxUserObject;
    //
    //
    //    [[UploadFile sharedInstance] wxUploadFileName:fileURL msgId:pre_messageId byUserJid:jidNameValid progress:self CompleteBlock:^(NSString *state,NSString *fileName,NSString *msgId) {
    //        if([state isEqualToString:@"success"])
    //        {
    //            //Message协议类型 普通文本数据存储(type=1,只数据库存储用) 图片type=2 视频type=3 音频type=4 普通文件type=5
    //            [self sendDescribeMsgId:pre_messageId msgbody:desc toContact:jidNameValid localfileName:localfilename serverFileName:fileName fileType:@"5" isGroupChat:isyes duration:0];
    //        }
    //        else
    //        {
    //            if (self.delegate && [self.delegate respondsToSelector:@selector(sendMessageRspState:messageId:error:)]) {
    //                [self.delegate sendMessageRspState:Chat_Send_Failure messageId:pre_messageId error:[NSString stringWithFormat:@"%@ 普通文件发送失败",fileName]];
    //            }
    //        }
    //    }];
    
    return pre_messageId;
}
/**
 *  上传到IM服务器成功之后 －－发送文件--
 *
 *  @param messageID     消息id
 *  @param messageBody   消息文本
 *  @param contactID     聊天对象的id
 *  @param localFileName 本地文件路径 －－用于展示、播放等
 *  @param serviceUrl    上传文件之后网络文件路径 －－用于展示、播放等
 *  @param fileType      文件类型
 *  @param isyes         是否是群聊 YES 群聊 NO 个人
 *  @param duration      时长，针对音频或视频
 */
- (void)sendFilesWithMsgID:(NSString *)messageID
               messageBody:(NSString *)messageBody
               toContactID:(NSString *)contactID
             localFileName:(NSString *)localFileName
                 servieUrl:(NSString *)serviceUrl
                  fileType:(NSString *)fileType
                  fileSize:(long)fileSize
               isGroupChat:(BOOL)isyes
                  duration:(NSInteger)duration
{

    
    NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
    [message addAttributeWithName:@"id" stringValue:messageID];
    [message addAttributeWithName:@"to" stringValue:contactID];
    
    NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
    [body setStringValue:serviceUrl];
    
    NSXMLElement *contentType = [NSXMLElement elementWithName:@"contentType"];
    [contentType setStringValue:fileType];
    
    NSXMLElement *fileName = [NSXMLElement elementWithName:@"fileName"];
    [fileName setStringValue:[localFileName lastPathComponent]];
    
    NSXMLElement *fileContentSize = [NSXMLElement elementWithName:@"fileSize"];
    [fileContentSize setStringValue:[NSString stringWithFormat:@"%ld",fileSize]];
    
    NSXMLElement *fileDuration = [NSXMLElement elementWithName:@"duration"];
    [fileDuration setStringValue:[NSString stringWithFormat:@"%ld",duration]];
    
    
    NSString *contactName = nil;
    if (isyes)
    {
        [message addAttributeWithName:@"type" stringValue:@"groupchat"];
        contactName = [ChatGroupMgr fetchGroupNameByGroupId:[Utility getBareContactId:contactID]];
    }
    else
    {
        [message addAttributeWithName:@"type" stringValue:@"chat"];
        contactName = [ChatContactMgr fetchNameByContactId:[Utility getBareContactId:contactID]];
    }
    
    
//    [message addChild:ext];
    [message addChild:body];
    [message addChild:contentType];
    [message addChild:fileName];
    [message addChild:fileContentSize];
    [message addChild:fileDuration];
    
    NSXMLElement *request = [NSXMLElement elementWithName:@"request" xmlns:@"urn:xmpp:receipts"];
    [message addChild:request];
    NSInteger messageType;
    //创建ChatMessage对象并保存到数据库表
    MessageBase *wxmsg  = [[MessageBase alloc] init];
    wxmsg.messageId     = messageID;
    
    if([fileType hasPrefix:@"image"]){
        //图片
        messageType = ChatMsgBody_Image;
        
    }else  if([fileType hasPrefix:@"audio"]){
        //语音
        messageType = ChatMsgBody_Voice;
        
        
    }else  if([fileType hasPrefix:@"video"]){
        //视频
        messageType = ChatMsgBody_Video;
        
        
    }else  if([fileType hasPrefix:@"*/*"]){
        //文件
        messageType = ChatMsgBody_File;
        
    }else{
        messageType = ChatMsgBody_Text;
        
    }

    
    wxmsg.messageType   = messageType;
    wxmsg.messageBody   = messageBody;
    wxmsg.createTime    = [NSString stringFromDate:[NSDate date]];

    wxmsg.messageStatus = Chat_Send_Sending;
    wxmsg.contactId     = [Utility getBareContactId:contactID];

    wxmsg.contactName   = contactName;
    wxmsg.isIncoming    = Msg_Out;
    wxmsg.isGroupMsg    = isyes;
    wxmsg.frommemberID = kUserLoginName;

    wxmsg.isRead = YES;
    wxmsg.duration = duration;
    if ([fileType integerValue] >=100)
    {
        wxmsg.messageBody = None;
        wxmsg.content = messageBody;
    }
    else
    {
        wxmsg.content = None;
    }
    wxmsg.localFileUrl = [localFileName lastPathComponent];
    wxmsg.serverFileName = serviceUrl;
    wxmsg.fileSize = 0;
    wxmsg.fileName = [localFileName lastPathComponent];
    
    [ChatMessageMgr saveChatMessageObj:wxmsg];
    
    [[UcfgroupXMPPManger sharedInstance].xmppStream sendElement:message];
    
    //将要发送消息
    [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Sending messageId:wxmsg.messageId error:nil];
    
    id messageObj = [[UcfgroupXMPPManger sharedInstance] distributeMsgType:wxmsg.messageType message:wxmsg];
    [[UcfgroupXMPPManger sharedInstance] addXmppRecordReqId:messageID type:@"sendMessageRspState:messageId:error:" paraMsg:messageObj];
    
    return;

}
/**
 *  发送收藏的消息
 *
 *  @param contactID
 *  @param messageText
 *  @param fileType      消息类型  //
 *  @param servieUrl     服务器路径
 *  @param localFileName 本地路径
 *  @param fileSize      文件大小
 *  @parm  isGroup    YES
 */
- (NSString *)sendCollectMessageContactID:(NSString *)contactID
                            message:(NSString *)messageText
                           filetype:(NSString *)fileType
                         serviceUrl:(NSString *)servieUrl
                           fileName:(NSString *)localFileName
                           fileSize:(NSInteger)fileSize
                            isGroup:(BOOL)isGroup
{
    //text/plain：纯文本 image/*：图片 audio/*：语音 video/*视频 */*：文件

    NSString *contentTypeStr;
    if ([fileType integerValue] == 0) {
        //文本
        contentTypeStr = @"text";
        NSString *contentMessageID =  [self sendMessageText:messageText
                                                  toContact:contactID
                                                isGroupChat:isGroup
                                                   delegate:self];
        return contentMessageID;
        
        
    }
    NSString *messageBody;
    if ([fileType integerValue] == 1) {
        //图片
        contentTypeStr = @"image";
        messageBody = @"图片";

    }
    if ([fileType integerValue] == 2) {
        //小视频
        contentTypeStr = @"video";
        messageBody = @"小视频";


    }
    if ([fileType integerValue] == 3) {
        //文件
        contentTypeStr = @"*/*";
        messageBody = @"文件";


    }
    
    
    NSString *messageId = [NSString stringWithFormat:@"%@_%d",[NSString stringFromDate:[NSDate date]],\
                           [self getRandomNumber:1000000 to:9000000]];
    NSString *jidNameValid = [self convertToJid:contactID isGroup:isGroup];

    [self sendFilesWithMsgID:messageId
                 messageBody:messageBody
                 toContactID:jidNameValid
               localFileName:localFileName
                   servieUrl:servieUrl
                    fileType:contentTypeStr
                    fileSize:fileSize
                 isGroupChat:isGroup
                    duration:0];
    return messageId;
    
}

//Message协议类型 普通文本数据存储(type=1,只数据库存储用) 图片type=2 视频type=3 音频type=4 普通文件type=5

- (void)sendDescribeMsgId:(NSString *)messageId
                  msgbody:(NSString *)messageBody
                toContact:(NSString *)contactId
            localfileName:(NSString *)localName
           serverFileName:(NSString *)sFileName
                 fileType:(NSString *)fileType
              isGroupChat:(BOOL)isyes
                 duration:(NSInteger)duration
{
    NSString *filename = [localName lastPathComponent];
    
    NSXMLElement *ext = [NSXMLElement elementWithName:@"ext"];
    [ext addAttributeWithName:@"type" stringValue:fileType];
    NSXMLElement *content = [NSXMLElement elementWithName:@"content"];
    
    long long fileSize = [self fileSizeAtPath:localName];    //服务器文件名称    本地文件名称        大小        持续
    NSString *sendFileDescribe = [NSString stringWithFormat:@"%@:%@:%ld:%ld",sFileName,filename,(long)(fileSize),(long)duration];
    [content setStringValue:sendFileDescribe];
 
    [ext addChild:content];
    
    NSXMLElement *message = [NSXMLElement elementWithName:@"message"];
    [message addAttributeWithName:@"id" stringValue:messageId];
    [message addAttributeWithName:@"to" stringValue:contactId];
    
    NSString *contactName = nil;
    if (isyes)
    {
        [message addAttributeWithName:@"type" stringValue:@"groupchat"];
        contactName = [ChatGroupMgr fetchGroupNameByGroupId:[Utility getBareContactId:contactId]];
    }
    else
    {
        [message addAttributeWithName:@"type" stringValue:@"chat"];
        contactName = [ChatContactMgr fetchNameByContactId:[Utility getBareContactId:contactId]];
    }

    
    [message addChild:ext];
    
    NSXMLElement *request = [NSXMLElement elementWithName:@"request" xmlns:@"urn:xmpp:receipts"];
    [message addChild:request];
    
    //创建ChatMessage对象并保存到数据库表
    MessageBase *wxmsg = [[MessageBase alloc] init];
    wxmsg.messageId = messageId;
    wxmsg.messageType = [fileType integerValue];
    wxmsg.messageBody = messageBody;
    wxmsg.createTime = [NSString stringFromDate:[NSDate date]];
    
    wxmsg.messageStatus = Chat_Send_Sending;
    wxmsg.contactId = [Utility getBareContactId:contactId];

    wxmsg.contactName = contactName;
    wxmsg.isIncoming = Msg_Out;
    wxmsg.isGroupMsg = isyes;
    
    wxmsg.isRead = YES;
    wxmsg.duration = duration;
    if ([fileType integerValue] >=100)
    {
        wxmsg.messageBody = None;
        wxmsg.content = messageBody;
    }
    else
    {
        wxmsg.content = None;
    }
    wxmsg.thumbnail = sFileName;
    wxmsg.localFileUrl = sFileName;
    
    wxmsg.serverFileName = sFileName;
    wxmsg.fileSize = 0;
    wxmsg.fileName = filename;
    
    [ChatMessageMgr saveChatMessageObj:wxmsg];
    
    [[UcfgroupXMPPManger sharedInstance].xmppStream sendElement:message];
    
    //将要发送消息
    [[UcfgroupXMPPManger sharedInstance] willSendMessageCallbackState:Chat_Send_Sending messageId:wxmsg.messageId error:nil];
    
    id messageObj = [[UcfgroupXMPPManger sharedInstance] distributeMsgType:wxmsg.messageType message:wxmsg];
    [[UcfgroupXMPPManger sharedInstance] addXmppRecordReqId:messageId type:@"sendMessageRspState:messageId:error:" paraMsg:messageObj];
    
    return;
}


/*!
 @method
 @brief   下载普通文件、音频文件、视频文件、大图片文件
 @param   messageId   要下载附件消息的Id
 @param   progress 进度条的代理回调，若不用可以传nil
 @param   (void(^)(BOOL state, NSString *description)) 下载成功与否block返回
 @result
 */
- (void)downloadFileByMessageId:(NSString *)messageId progress:(id<IChatProgressDelegate>)progress completeBlock:(void(^)(BOOL state, NSString *filePath))complete
{
    if (messageId == nil || [messageId isEqualToString:@""]) {
        complete(NO,@"messageId_Error");
        return;
    }
    
    MessageBase *getObj = [ChatMessageMgr readChatMessageObjByMsgId:messageId];
    if (getObj == nil) {
        complete(NO,@"messageId_NotExist");
        return;
    }
    
    NSString *filePath = [self documentFolderPathAndFileName:getObj.fileName];
    if ([self isFileExist:filePath])
    {
        complete(YES,filePath);
        return;
    }
    
    self.delegateprogress = progress;
    
    NSString *picUrl = [NSString stringWithFormat:@"%@%@%@",[[UcfgroupXMPPManger sharedInstance] getFileServer],@"/file_download.yaws/files/big/",getObj.serverFileName];
    
    [HttpURLConnection request:picUrl progress:self completeBlock:^(NSData *data) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"fileName= %@",getObj.serverFileName);
            
            BOOL ret = [data writeToFile:filePath atomically:YES];
//            getObj.file
//            [ChatMessageMgr saveChatMessageObj:getObj];
            NSLog(@"ret = %d",ret);
            complete(YES,filePath);
        });
        
    } errorBlock:^(NSError *error) {
        NSLog(@"error %@",error);
        complete(NO,@"fail");
    }];
    
    return;
}

/*!
 @method
 @brief   下载大图片文件、小图片文件
 @param   fileName   要下载文件名称
 @param   imageType  0:默认小图片文件；1：大图片文件 imageType不是这两个值，返回Chat_imageType_Error
 @param   progress 进度条的代理回调，若不用可以传nil
 @param   (void(^)(BOOL state, NSString *filePath)) 下载成功与否block返回
 @result
 */
- (void)downloadImageFileByMessageId:(NSString *)messageId imageType:(NSInteger)imageType progress:(id<IChatProgressDelegate>)progress completeBlock:(void(^)(BOOL state, NSString *filePath))complete
{
    if (messageId == nil || [messageId isEqualToString:@""]) {
        complete(NO,@"Chat_fileName_Error");
        return;
    }
    
    if (imageType < 0 || imageType > 1) {
        complete(NO,@"Chat_imageType_Error");
        return;
    }
    
    MessageBase *getObj = [ChatMessageMgr readChatMessageObjByMsgId:messageId];
    if (getObj == nil) {
        complete(NO,@"messageId_NotExist");
        return;
    }
    
    NSString *filePath = [self documentFolderPathAndFileName:getObj.fileName];
    if ([self isFileExist:filePath])
    {
        complete(YES,filePath);
        return;
    }
    
    self.delegateprogress = progress;
    
    NSString *picUrl = nil;
    if(imageType == 0)
    {
        picUrl = [NSString stringWithFormat:@"%@%@%@",[[UcfgroupXMPPManger sharedInstance] getFileServer],@"/file_download.yaws/files/small/",getObj.serverFileName];
    }
    else
    {
        picUrl = [NSString stringWithFormat:@"%@%@%@",[[UcfgroupXMPPManger sharedInstance] getFileServer],@"/file_download.yaws/files/big/",getObj.serverFileName];
    }
    
    [HttpURLConnection request:picUrl progress:self completeBlock:^(NSData *data) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"fileName= %@",filePath);
            
            BOOL ret = [data writeToFile:filePath atomically:YES];
            NSLog(@"ret = %d",ret);
            complete(YES,@"success");
        });
        
    } errorBlock:^(NSError *error) {
        NSLog(@"error %@",error);
        complete(NO,@"fail");
    }];
    
    return;
}

/*
 处理进度的
 */
//- (void)setProgress:(float)newProgress
//{
//    //888888
//    WXLog(@"setProgress:%f",newProgress);
//    //progressView.progress = newProgress;
//    //currentPro.text = [NSString stringWithFormat:@"%.2fM",fileLength*newProgress];
//    
////    if (self.delegateprogress && [self.delegateprogress respondsToSelector:@selector(setProgress:forMessage:)]) {
////        [self.delegateprogress setProgress:newProgress forMessage:pre_messageId];
////    }
//}
//999999999
- (void)getProgress:(float)newProgress msgId:(NSString *)msgId
{
    //888888
    WXLog(@"setProgress:%f  msgId= %@",newProgress,msgId);
    //progressView.progress = newProgress;
    //currentPro.text = [NSString stringWithFormat:@"%.2fM",fileLength*newProgress];
    
    NSMutableDictionary *progressDic = [[NSMutableDictionary alloc] init];
    [progressDic setValue:[NSString stringWithFormat:@"%f",newProgress] forKey:@"newProgress"];
    [progressDic setValue:msgId forKey:@"msgId"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:kProgressUpdate object:progressDic];
    
//    if (self.delegateprogress && [self.delegateprogress respondsToSelector:@selector(setProgress:forMessage:)]) {
//        [self.delegateprogress setProgress:newProgress forMessage:msgId];
//    }
}

/*!
 @method
 @brief      从聊天记录中搜索与某个好友聊天的记录
 @param      userId联系人id或者群组id
 @discussion 同步方法
 @param      beginIndex开始索引值（index从0开始）
 @param      count：要获取的条数（如实际条数小于count，则返回实际条数） 若count为0，则表示默认：获取全部
 @result     参数为空或聊天记录为空，则返回nil，其他情况返回类型为GetChatMessage的对象数组
 */
- (NSMutableArray *)getConversationById:(NSString *)contactId beginIndex:(NSInteger)beginIndex count:(NSInteger)count
{
    if (contactId == nil || [contactId isEqualToString:@""]) {
        return nil;
    }
    
    NSString *validContactId = [self convertToJid:contactId isGroup:NO];
    //获取最近聊天过的联系人最新消息记录列表
    NSMutableArray *retArray = [ChatMessageMgr fetchMessageListWithUser:validContactId beginIndex:beginIndex count:count];
    return retArray;
}

/*!
 @method
 @brief      获取与某个联系人或群组聊天的未读消息个数
 @param      contactId联系人id或者群组id
 @discussion 同步方法
 @result     参数为空或聊天记录为空，则返回0，其他情况返回未读消息条数
 */
- (NSInteger)getUnreadMsgCountToContactId:(NSString *)contactId
{
    if (contactId == nil || [contactId isEqualToString:@""]) {
        return 0;
    }
    return [ChatMessageMgr fetchUnreadMsgCountToContactId:contactId];
}

/*!
 @method
 @brief       删除与某个好友的所有聊天记录
 @param       contactId 要删除聊天消息好友的Id
 @discussion  同步方法
 @result      返回成功or失败
 */
- (BOOL)deleteAllMessageToContactId:(NSString *)contactId
{
    BOOL ret = NO;
    if (contactId == nil || [contactId isEqualToString:@""]) {
        return ret;
    }
    
    NSString *validContactId = [self convertToJid:contactId isGroup:NO];
    ret = [ChatMessageMgr deleteAllMessageToContactId:validContactId];
    
    validContactId = [self convertToJid:contactId isGroup:YES];
    //获取最近聊天过的联系人最新消息记录列表
    ret = [ChatMessageMgr deleteAllMessageToContactId:[Utility getBareContactId:validContactId]];
    return ret;
}


/*!
 @method
 @brief       获取最近聊天过的联系人最新消息记录列表
 @discussion  同步方法
 @result      返回ChatRecent对象数组  （空则 返回nil）
 */
- (NSMutableArray *)getMyAllConversation
{
    //获取最近聊天过的联系人最新消息记录列表
    NSMutableArray *retArray = [ChatMessageMgr fetchRecentChatByPage:0];
    return retArray;
}


/*!
 @method
 @brief      设置消息状态为已读
 @param      messageId 要设置的消息Id
 @discussion 同步方法
 @result     成功:Chat_Success  失败:Chat_Failure messageId参数:Chat_msgId_Error (messageId不存在Or为空)
 */
- (NSString *)deleteMessage:(NSString *)messageId
{
    if (messageId == nil || [messageId isEqualToString:@""]) {
        return @"Chat_msgId_Error";
    }
    
    if(![ChatMessageMgr isFindTheMessageIdExist:messageId])
    {
        return @"Chat_msgId_Error";
    }
    
    BOOL ret = [ChatMessageMgr deleteMessageId:messageId];
    if (ret) {
        return @"Chat_Success";
    }
    else
    {
        return @"Chat_Failure";
    }

}

/*!
 @method
 @brief       设置消息状态为已读
 @param       messageId 要设置的消息Id
 @discussion  同步方法
 @result      成功:Chat_Success  失败:Chat_Failure messageId参数:Chat_msgId_Error (messageId不存在Or为空)
 */
- (NSString *)markMsgAsRead:(NSString *)messageId
{
    if (messageId == nil || [messageId isEqualToString:@""]) {
        return @"Chat_msgId_Error";
    }
    if(![ChatMessageMgr isFindTheMessageIdExist:messageId])
    {
        return @"Chat_msgId_Error";
    }
    
    BOOL ret = [ChatMessageMgr setTheMessageIsReaded:messageId];
    if (ret) {
        return @"Chat_Success";
    }
    else
    {
        return @"Chat_Failure";
    }
}


/*!
 @method
 @brief      获取所有未读消息列表
 @discussion 同步方法
 @result     返回ChatMessage对象数组
 */
- (NSMutableArray *)getAllUnreadedMessage
{
    //获取得到所有未读消息列表
    NSMutableArray *unreadArry = [ChatMessageMgr getAllUnReadMessageList];
    return unreadArry;
}

- (void)registDelegate:(id<EWxChatMgrChatDelegate>)delegate
{
    WXLog(@"registDelegate");
    self.delegate = delegate;
    [UcfgroupXMPPManger sharedInstance].xmppMsgDelegate = delegate;
}

- (void)unregistDelegate:(id<EWxChatMgrChatDelegate>)delegate
{
    WXLog(@"unregistDelegate");
    self.delegate = nil;
    [UcfgroupXMPPManger sharedInstance].xmppMsgDelegate = nil;
}

/*!
 @method
 @brief      同步方法设置消息是否已读状态
 @discussion 好友收到查看置为已读
 @param      messageId消息id
 @result
 */
- (BOOL)setTheMessageIsReaded:(NSString *)messageId
{
    WXLog(@"setTheMessageIsSendSuccess");
    return [ChatMessageMgr setTheMessageIsReaded:messageId];
}

/*!
 @method
 @brief      同步方法设置消息发送状态
 @discussion 服务器收到，对方收到，发送失败
 @param      messageId消息id isSendSuccess消息状态
 @result
 */
- (BOOL)setTheMessageIsSendSuccess:(NSString *)messageId withSendStatus:(NSString *)isSendSuccess
{
    WXLog(@"setTheMessageIsSendSuccess");
    return [ChatMessageMgr setTheMessageIsSendSuccess:messageId withSendStatus:isSendSuccess];
}

/*!
 @method
 @brief      同步方法获取与某联系人Id的聊天历史记录
 @param      userId联系人id或者群组id
 @param      beginIndex开始索引值（index从0开始）  
 @param      count：要获取的条数（如实际条数小于count，则返回实际条数） 若count为0，则表示默认：获取全部
 @result     参数为空或聊天记录为空，则返回nil，其他情况返回类型为GetChatMessage的对象数组
 */
- (NSMutableArray*)fetchMessageListWithUser:(NSString *)userId beginIndex:(NSInteger)beginIndex count:(NSInteger)count
{
    if (userId == nil ||[userId isEqualToString:@""]) {
        return nil;
    }
    if (beginIndex < 0 || count < 0) {
        return nil;
    }
    return [ChatMessageMgr fetchMessageListWithUser:[Utility getBareContactId:userId] beginIndex:beginIndex count:count];
}

#pragma mark - 发送收藏信息－－－－





#pragma mark-------------------------通用处理方法-----------------------------
- (NSString *)convertToJid:(NSString *)jidName isGroup:(BOOL)isyes
{
    NSString *jidNameValid = nil;
    NSString *domain = kXMPPmyDomain;
    if (isyes) {
        domain = kXMPPAndGroupDomain;
    }
    
    jidNameValid = [NSString stringWithString:jidName];
    NSRange range = [jidNameValid rangeOfString:kXMPPmyDomain];
    if (range.length >0)//包含
    {
        jidNameValid = [jidNameValid substringToIndex:range.location];
    }
    range = [jidNameValid rangeOfString:kXMPPAndGroupDomain];
    if (range.length >0)//包含
    {
        jidNameValid = [jidNameValid substringToIndex:range.location];
    }
    
    jidNameValid = [NSString stringWithFormat:@"%@%@",jidNameValid,domain];
    
    WXLog(@"convertToJid: jidNameValid= %@ isGroup: %d",jidNameValid,isyes);
    return jidNameValid;
}

//获取一个随机整数，范围在[from,to），包括from，不包括to
-(int)getRandomNumber:(int)from to:(int)to
{
    return (int)(from + (arc4random() % (to - from + 1))); //+1,result is [from to]; else is [from, to)!!!!!!!
}
- (BOOL)isFileExist:(NSString *)fileName
{
    if (fileName == nil || [fileName isEqualToString:@""]) {
        return NO;
    }
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
//    NSString *path = [paths objectAtIndex:0];
//    NSString *filePath=[path stringByAppendingPathComponent:fileName];
    NSString *filePath = fileName;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    return result;
}

//获取单个文件的大小
- (unsigned long long)fileSizeAtPath:(NSString*) filePath
{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

- (NSString *)documentFolderPathAndFileName:(NSString *)fileName
{
    //本地保存-png格式 - by Vince
    NSString *documentsDirectory=DATABASE_PATH;
    NSString *savedImagePath=[documentsDirectory stringByAppendingPathComponent:fileName];
    return savedImagePath;
}

@end
